package com.ruoyi.web.controller.business;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Sales;
import com.ruoyi.business.domain.SalesDetailItem;
import com.ruoyi.business.service.ISalesService;
import com.ruoyi.business.service.ISalesDetailItemService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 销售Controller
 * 
 * @author ruoyi
 * @date 2025-04-01
 */
@RestController
@RequestMapping("/business/sales")
public class SalesController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(SalesController.class);
    
    @Autowired
    private ISalesService salesService;
    
    @Autowired
    private ISalesDetailItemService salesDetailItemService;

    /**
     * 查询销售列表
     */
    @PreAuthorize("@ss.hasPermi('business:sales:list')")
    @GetMapping("/list")
    public TableDataInfo list(Sales sales)
    {
        startPage();
        List<Sales> list = salesService.selectSalesList(sales);
        return getDataTable(list);
    }

    /**
     * 导出销售列表
     */
    @PreAuthorize("@ss.hasPermi('business:sales:export')")
    @Log(title = "销售", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Sales sales)
    {
        List<Sales> list = salesService.selectSalesList(sales);
        ExcelUtil<Sales> util = new ExcelUtil<Sales>(Sales.class);
        util.exportExcel(response, list, "销售数据");
    }

    /**
     * 获取销售详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:sales:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        Sales sales = salesService.selectSalesById(id);
        
        // 查询销售单明细
        if (sales != null) {
            SalesDetailItem query = new SalesDetailItem();
            query.setSalesId(id);
            List<SalesDetailItem> itemList = salesDetailItemService.selectSalesDetailItemList(query);
            sales.setSalesDetailItemList(itemList);
        }
        
        return success(sales);
    }

    /**
     * 根据单据编号查询销售单信息
     */
    @PreAuthorize("@ss.hasPermi('business:sales:query')")
    @GetMapping(value = "/receipt/{receiptCode}")
    public AjaxResult getInfoByReceiptCode(@PathVariable("receiptCode") String receiptCode)
    {
        Sales sales = salesService.selectSalesByReceiptCode(receiptCode);
        
        // 查询销售单明细
        if (sales != null) {
            List<SalesDetailItem> itemList = salesDetailItemService.selectSalesDetailItemsByReceiptCode(receiptCode);
            sales.setSalesDetailItemList(itemList);
        }
        
        return success(sales);
    }

    /**
     * 新增销售
     */
    @PreAuthorize("@ss.hasPermi('business:sales:add')")
    @Log(title = "销售", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Sales sales)
    {
        try {
            Long userId = getLoginUser().getUserId();
            sales.setUserId(userId);
            int rows = salesService.insertSales(sales);
            return toAjax(rows);
        } catch (Exception e) {
            log.error("保存销售单失败", e);
            return AjaxResult.error("保存销售单失败: " + e.getMessage());
        }
    }

    /**
     * 修改销售
     */
    @PreAuthorize("@ss.hasPermi('business:sales:edit')")
    @Log(title = "销售", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Sales sales)
    {
        try {
            int rows = salesService.updateSales(sales);
            return toAjax(rows);
        } catch (Exception e) {
            log.error("修改销售单失败", e);
            return AjaxResult.error("修改销售单失败: " + e.getMessage());
        }
    }

    /**
     * 删除销售
     */
    @PreAuthorize("@ss.hasPermi('business:sales:remove')")
    @Log(title = "销售", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        System.out.println(ids);
        for (int i = 0; i < ids.length; i++) {
            System.out.println(ids);
        }
        return toAjax(salesService.deleteSalesByIds(ids));
    }
}
